<script setup>
import { ref, resolveComponent } from 'vue';
import { onMounted, onUpdated } from 'vue'; // 添加对onMounted的导入
import { coldStorageListService } from '@/api/coldStorage.js';

//分页条数据模型
const pageNum = ref(1); //当前页
const total = ref(); //总条数
const pageSize = ref(5); //每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = async (size) => {
    pageSize.value = size;
    await getColdStorages();
    // 更新ECharts图表
    updateEChartsCharts(coldStorages.value);//没用，先于dom
};
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
    pageNum.value = num;
    await getColdStorages();
    // 更新ECharts图表
    updateEChartsCharts(coldStorages.value);//好耶对了

};
const coldStorages = ref([])

const getColdStorages = async () => {
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        type: null,
        state: null
    };
    let result = await coldStorageListService(params);
    //渲染到视图上
    total.value = result.data.total;
    coldStorages.value = result.data.items;
    // 使用for...of循环为coldStorages中的每个对象添加stateName字段
    for (let c of coldStorages.value) {
        c.stateName = systemParameter.getColdStorageStateName(c.state);
        c.oper = systemParameter.getColdStorageOperation(c.state);
    }

}


//echarts的初始化和销毁
function updateEChartsCharts(coldStorages) {
    const existingChartIds = new Set();

    coldStorages.forEach((coldStorage) => {

        // 定义所需数据
        const shelves = coldStorage.shelves;
        const occupied = coldStorage.occupied;
        const unoccupied = shelves - occupied;

        // 计算容量与库存比例
        const ratio = (occupied / shelves * 100) ? (occupied / shelves * 100) : 0;
        console.log(ratio);
        // 配置单个柱状图系列，堆叠模式
        const series = [
            {
                // name: '已用货架',
                type: 'bar',
                stack: '总量', // 共享同一堆叠模式标识
                data: [occupied], // 数据数组只包含已用货架数
                label: {
                    show: true,
                    formatter: (params) => `${Math.round(params.value)}` // 标签内容为整数形式的货架数
                },
                itemStyle: {
                    color: '#e97209' // 已用货架颜色为橙色
                }
            },
            {
                // name: '空闲货架',
                type: 'bar',
                stack: '总量', // 堆叠模式标识，所有堆叠柱状图需共享同一标识
                data: [unoccupied], // 数据数组只包含空闲货架数
                label: {
                    show: true,
                    formatter: (params) => `${Math.round(params.value)}` // 标签内容为整数形式的货架数
                },
                itemStyle: {
                    color: '#91cc75' // 空闲货架颜色为绿色
                }
            },
        ];
        // 百分比容量图表配置
        const option = {
            tooltip: {
                trigger: 'axis', // 触发方式为坐标轴触发（默认值，可省略）
                axisPointer: {
                    type: 'shadow' // 坐标轴指示器类型为阴影指示器（默认值，可省略）
                },
                formatter: `${'空闲'}: ${unoccupied}\n${'已用'}: ${occupied}`, // 返回格式化后的提示内容
            },

            legend: {},
            grid: {
                left: 100,
                right: 100,
                top: 0,
                bottom: 20
            },
            yAxis: {
                type: 'value',
                min: 0, // 设置最小值为0，确保比例显示在合理范围内
                max: shelves ? shelves : 0, // 设置最大值为1，对应100%比例
                // interval: 10, // 可视化时，y轴刻度间隔设置为10个货架
                axisLabel: {
                    formatter: '{value}'
                } // 格式化y轴标签
            },
            xAxis: {
                type: 'category',
                data: ['货架'], // x轴数据标签为“空闲”和“已用”
                axisLabel: {
                    rotate: 0
                }
            },
            series
        };

        const chartContainer = document.getElementById('chart-' + coldStorage.id); // 更改ID匹配逻辑
        if (!chartContainer) {
            console.error(`未能找到ID为"chart-${coldStorage.id}"的容器元素`);
            return;
        }

        // 如果图表容器已存在且已有ECharts实例，则更新数据
        const myChart = echarts.getInstanceByDom(chartContainer);
        if (myChart) {
            existingChartIds.add(coldStorage.id);
            myChart.setOption(option);
        } else {
            // 否则，创建新的ECharts实例
            const myChart = echarts.init(chartContainer);
            myChart.setOption(option);
        }
    });

    // 销毁不再存在的冷库存储对应的ECharts实例
    if (echarts && echarts.instances) {
        const existingCharts = echarts.instances.filter(
            (chart) => !existingChartIds.has(chart.id)
        );
        existingCharts.forEach((chart) => chart.dispose());
    }
}

import {
    Edit, Delete,
    Check,
    Message,
    Search,
    Star, Close, InfoFilled

} from "@element-plus/icons-vue";

import Pass from '@/assets/pass.png'
import Reject from '@/assets/reject.png'
import { applicationListService } from '@/api/message.js'
import useSystemParameter from '@/stores/useSystemParameter.js'
import { ElMessage, IconMap } from 'element-plus';
const systemParameter = useSystemParameter();





import * as echarts from 'echarts';
import UserInfo from '../user/UserInfo.vue';


// 基于准备好的dom，初始化echarts实例
// var myChart = echarts.init(document.getElementById('main'));
// 绘制图表
// const option = {
//   title: {
//     text: 'ECharts 入门示例'
//   },
//   tooltip: {},
//   xAxis: {
//     data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
//   },
//   yAxis: {},
//   series: [
//     {
//       name: '销量',
//       type: 'bar',
//       data: [5, 20, 36, 10, 10, 20]
//     }
//   ]
// };
// 在mounted生命周期钩子中初始化ECharts实例
onMounted(async () => {
    //正确加载需要的数据准备
    await getColdStorages();
    await getSensorList();
    // 更新ECharts图表；要先有dom才可以运行
    updateEChartsCharts(coldStorages.value);
    // coldStorages.value.forEach((coldStorage) => {
    //     const chartContainer = document.getElementById(String(coldStorage.id));
    //     if (!chartContainer) {
    //         console.error(`未能找到ID为"${coldStorage.id}"的容器元素`);
    //         return;
    //     }
    //     const myChart = echarts.init(chartContainer);
    //     myChart.setOption(option);
    // });

});

let sensorList = ref([]);
let visibleColdStorage = ref();//选中冷库
const initialDialog = ref(false)//编辑框
import { sensorListService, sensorUpdateService, coldStorageInitialService, coldStorageRecreateService } from '@/api/coldStorage.js';
//重置冷库
const recreate = async (c) => {
    const result = await coldStorageRecreateService(c.id)
    if (result.code === 0) {
        ElMessage.success(result.message ? result.message : "重建冷库成功")
        await getColdStorages();
        await getSensorList();
        updateEChartsCharts(coldStorages.value);
    }
}
const chooseType = ref("refrigerate")//冷藏库？否则速冻库
const getSensorList = async () => {
    let params = {
        pageNum: 1,
        pageSize: 10000,
        searchString: chooseType.value === 'freeze' ? "温度" : null
    }
    console.log(params.searchString)
    console.log(chooseType)
    const result = await sensorListService(params);
    sensorList = result.data.items;

}
const loading1 = ref(false)
const beforeChange1 = async () => {
    loading1.value = true;
    if (chooseType.value === "freeze") {
        chooseType.value = "refrigerate"
        await getSensorList();
        return new Promise((resolve) => {
            chooseType.value = "freeze"//改回去
            // ElMessage.success('Switch success')
            loading1.value = false;
            return resolve(true)
        })
    } else {
        chooseType.value = "freeze"
        await getSensorList();
        return new Promise((resolve) => {
            chooseType.value = "refrigerate"//改回去
            // ElMessage.success('Switch success')
            loading1.value = false;
            return resolve(true)
        })
    }
}

//传感器绑定
const renewSensor = async (sensor) => {
    const result = await sensorUpdateService(sensor)
    if (result.code === 0) {
        ElMessage.success(result.message ? result.message : "传感器更新成功")
        getColdStorages();
    }
}


//货架数设置
const setShelves = async (c) => {

}

//初始化冷库
const initial = async (c) => {
    //更新状态到idling
    console.log(c.id);
    const result = await coldStorageInitialService(c.id, chooseType.value);
    if (result.code === 0) {
        ElMessage.success(result.message ? result.message : "初始化成功");
        getColdStorages();
        console.log(initialDialog.value)
        initialDialog.value = false;
    }
}


import humidityIcon from '@/assets/humidity.png'//湿度图标
import temperatureIcon from '@/assets/temperature.png'//湿度图标
import freezeIcon from '@/assets/select_freeze.png'//速冻图标
import refrigerate from '@/assets/select_refrigerate.png'//冷藏图标
console.log(systemParameter.roles);
</script>


<template>
    <el-card class="page-container" position='relative'>
        <template #header>
            <div class="header">
                <span> 新建、前往维修、维修验收、拆除</span>
                <div class="extra">
                    <el-button type="primary" @click="showApply = !showApply">新增申请</el-button>
                </div>
            </div>
        </template>
        <!-- echarts -->
        <!-- <div id="main" style="width: 100%; height: 400px" class="chart-item"></div> -->

        <h2>全部冷库 </h2>
        <div class="cold-storage-list-container">
            <div v-for="c of coldStorages" class="cold-storage-container">
                <!-- 图片跳转 -->
                <div href="" class="cold-storage-background">
                    <!-- 使用唯一ID，并移除内部v-for循环 -->

                    <div class="image-container">
                        <el-tooltip ceffect="dark" :content="c" placement="top-start">
                            <img :src="'/src/assets/type_' + c.type + '.png'" alt="冷库类型图标"
                                style="width: 100%; height: 80%;">
                        </el-tooltip>
                        <el-tooltip ceffect="dark" :content="c.stateName" placement="top-start">
                            <div class="icon-overlay">
                                <img class="status-icon" :src="'/src/assets/state_' + c.state + '.png'" alt="冷库状态图标" />
                            </div>
                        </el-tooltip>
                    </div>

                    <div class="cold-storage-name">{{ c.name }}</div>
                </div>

                <!-- 容量条 -->
                <div :id="'chart-' + c.id" class="chart-item" style="width: 15%;height: 55%;" @click="setShelves(c)">
                </div>


                <!-- 这里
                工程师类型权限：    systemParameter.getCurrentUserRole()['/coldstorage/construct'] === 1
                冷库使用者类型权限：systemParameter.getCurrentUserRole()['/coldstorage/use'] === 1

                对应状态可以有的操作：    c.oper.initial === 1
                -->

                <!-- 冷库重置：工程师 + 任意状态 -->
                <el-tooltip content="重置" placement="bottom" effect="dark">
                    <el-button plain type="primary" class="button-with-image test-item" @click="recreate(c)"
                        v-if="systemParameter.getCurrentUserRole()['/coldstorage/construct'] === 1">
                        <img src="@/assets/to_recreate.png" class="button-image"
                            style="object-fit: cover; border-radius: 50%;" />
                    </el-button>
                </el-tooltip>


                <!-- 冷库初始化initial：工程师 +  creating-->
                <el-tooltip content="初始化配置" placement="bottom" effect="dark">
                    <el-button plain type="primary" class="button-with-image test-item" v-if="c.oper.initial === 1 && systemParameter.getCurrentUserRole()['/coldstorage/construct'] === 1"
                        @click="initialDialog = true; visibleColdStorage = c">
                        <img src="@/assets/to_initial.png" class="button-image" />
                    </el-button>
                </el-tooltip>

                <!-- 冷库运行run：用户 +  idling-->
                <el-tooltip content="运行" placement="bottom" effect="dark">
                    <el-button plain type="primary" class="button-with-image test-item" v-if="c.oper.run === 1 && systemParameter.getCurrentUserRole()['/coldstorage/use'] === 1"
                        @click="initialDialog = true; visibleColdStorage = c"
                        >
                        <img src="@/assets/to_run.png" class="button-image" />
                    </el-button>
                </el-tooltip>




                <div class="test-item"></div>
                <div class="test-item"></div>
                <div class="test-item"></div>
                <div class="test-item"></div>
                <div class="test-item"></div>
                <div class="test-item"></div>
                <div class="test-item"></div>
                <div class="test-item"></div>





                <!-- <div class="cold-storage-name">{{ c.name }}</div> -->

            </div>
        </div>


        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[4, 8, 16, 32, 64, 128]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />


        <el-dialog v-model="initialDialog" :title='title' width="800">
            <!-- 冷库初始化 -->
            <div style="display: flex;justify-content: space-between">
                <div>初始化配置：
                    <el-switch v-model="chooseType" active-text="速冻（<0℃）" active-value="freeze"
                        :before-change="beforeChange1" inactive-text="冷藏（>0℃）" inactive-value="refrigerate"
                        :loading="loading1">
                        <template #active-action>
                            <span class="custom-active-action">
                                <img :src="freezeIcon" class="el-icon-img">
                            </span>
                        </template>
                        <template #inactive-action>
                            <span class="custom-inactive-action">
                                <img :src="refrigerate" class="el-icon-img">
                            </span>
                        </template>
                    </el-switch>
                </div>
                <el-popconfirm :title="'确定要用已绑定的传感器来初始化一个' + (chooseType === 'freeze' ? '速冻' : '冷藏') + '冷库?'"
                    @confirm="initial(visibleColdStorage)" @cancel="">
                    <template #reference>
                        <el-button @click="">初始化完成</el-button>
                    </template>
                </el-popconfirm>

            </div>

            <!-- 传感器绑定 -->
            <el-table :data="sensorList" max-height="600">
                <el-table-column width="180" property="id" label="id" />
                <el-table-column width="180" property="name" label="传感器名" />
                <el-table-column width="100" property="sensorName" label="类型" #default="{ row }">
                    {{ row.sensorName }}
                    <el-icon class="custom-itom" v-if="row.sensorName !== '应激指数'">
                        <img :src="row.sensorName === '温度' ? temperatureIcon : row.sensorName === '湿度' ? humidityIcon : null"
                            class="el-icon-img">
                    </el-icon>

                </el-table-column>
                <el-table-column label="绑定操作" #default="{ row }">
                    <div v-if="visibleColdStorage.id === row.CSId">
                        <el-tag type="success">已绑定</el-tag>
                        <el-button type="primary" @click="row.CSId = null; renewSensor(row)">
                            解绑
                        </el-button>
                    </div>
                    <div v-else-if="!row.CSId">
                        <el-tag :label="'可选'" type="info">可绑定</el-tag>
                        <el-button type="primary"
                            @click="row.CSId = visibleColdStorage.id; renewSensor(row)">绑定</el-button>
                    </div>
                    <div v-else>
                        <el-tag type="danger">被其他冷库绑定</el-tag>
                    </div>

                </el-table-column>

            </el-table>


            <!-- <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="updateUser(editUser), dialogVisible = false"> 确认
                    </el-button>
                </span>
            </template> -->
        </el-dialog>

    </el-card>
</template>



<style scoped>
.el-carousel__item h3 {
    color: #475669;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
    text-align: center;
}

.el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
    background-color: #d3dce6;
}

.page-container {
    min-height: 100%;
    min-width: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}


.cold-storage-list-container {
    height: 100%;
    margin: 0 3% 4% 0;
    /* float: left; */
    position: relative;
    transition: 0.5s all;
    -webkit-transition: 0.5s all;
    -moz-transition: 0.5s all;
    -o-transition: 0.5s all;
    min-height: 100px;
    min-width: 100px;
    /* 删 */
    border: 2px solid #d71414;
    display: flex;
    /* 让子元素自动换行 */
    flex-wrap: wrap;
    /* 设置内容靠左对齐 */
    justify-content: flex-start;
}

.cold-storage-container {
    width: 150px;
    height: 200px;
    /* 删 */
    border: 0.1px solid #090404;
    display: flex;
    /* 换行 */
    flex-wrap: wrap;
    /* justify-content: flex-start; */
    /* 设置内容靠右对齐 */
    margin: 1%;

}

.cold-storage-background {
    width: 75%;
    height: 60%;
}

.image-container {
    position: relative;
    display: inline-block;
}



.icon-overlay {
    position: absolute;
    /* 调整为适当距离，使图标离图片底部有一定间隔 */
    bottom: 0px;
    /* 调整为适当距离，使图标离图片右侧有一定间隔 */
    right: 20px;
    /* 向左上方移动一定距离，负值表示向反方向移动 */
    /* margin: 10px; */
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    gap: 10px;
    /* 调整图标间的间距 */
    /* pointer-events: none; */
    /* 避免图标遮挡图片的鼠标交互 */
}

.icon-overlay img {
    width: 24px;
    /* 设置合适的图标大小 */
    height: auto;
}



.cold-storage-name {
    text-align: center;
    /* 文本居中 */
    font-size: max(1vw, 0.05rem);
    /* 字体大小自动调整，最小为1rem（16px），最大为容器宽度的5% */
    white-space: nowrap;
    /* 避免文本换行 */
    overflow: hidden;
    /* 隐藏超出容器的文本 */
    text-overflow: ellipsis;
    /* 显示省略号表示文本被截断 */
}

.chart-item {
    /* flex-grow: 1; */
    /* 占满可用空间 */
    margin: 5%;
    /* 可选，添加间距 */
    /* border: 0.1px solid #d71414; */
    flex-wrap: wrap;
    justify-content: flex-start;
}

.text-item-container {
    flex-grow: 1;
    border: 0.1px solid #d71414;
}

/* 化成上面那种 */
.test-item {
    margin: 1%;
    border: 0.1px solid #d71414;
    flex-wrap: wrap;
    justify-content: flex-start;
    width: 15%;
    height: 12%;
}


/* //图像按钮 */
.button-with-image {
    position: relative;
    /* // border:1px solid rgb(23, 110, 172); */
    /* 确保按钮内部的定位基于按钮本身 */
    padding: 0;
    /* 根据需要调整内边距以适应图像 */
}

.button-with-image .button-image {
    max-width: 100%;
    /* 限制图像的最大宽度 */
    max-height: 100%;
    /* 限制图像的最大高度 */
    display: block;
    /* 避免底部的空白间隙 */
    /* border-radius: 50%; */
    /* 使图像显示为圆形 */
}
</style>